package cn.fancy.sdk.login.view;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.fancy.sdk.FancyManager;
import cn.fancy.sdk.baseview.BaseView;
import cn.fancy.sdk.baseview.IActivityManager;
import cn.fancy.sdk.common.utils.NetworkImpl;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.common.utils.SdkAsyncTask;
import cn.fancy.sdk.entity.GuildBaseInfo;
import cn.fancy.sdk.login.DeleteUserDialog;
import cn.fancy.sdk.login.DeleteUserDialog.DeleteCallback;
import cn.fancy.sdk.login.utils.AccountHelper;
import cn.fancy.sdk.login.utils.AccountHelper.Local_Account;
import cn.fancy.sdk.login.utils.DBHelper;
import cn.fancy.sdk.login.utils.HttpReq;
import cn.fancy.sdk.utils.CommMessage;
import cn.fancy.sdk.utils.TipMessSingle;
import java.util.ArrayList;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class FindPassMain extends BaseView implements OnItemClickListener {
    
    private IActivityManager activityMgr;
    private Activity ownerActivity;
    private Context mContext;
    private LayoutInflater inflater;
    private DBHelper dbHelper;
    private String ucode = "";
    private Timer timer;
    private Handler handler;
    private SdkAsyncTask<String> bindPhoneAsyncTask = null;
    private EditText phone_input, code_input;
    private TextView mSendMess;
    
    private ArrayList<FindPassMain.Account> acctArray = new ArrayList<FindPassMain.Account>();
    private ArrayList<DBHelper.SDK_ACCOUNT> db_valid_accts = new ArrayList<DBHelper.SDK_ACCOUNT>();
    ArrayList<AccountHelper.Local_Account> local_valid_accts = new ArrayList<AccountHelper.Local_Account>();
    private AccountShowAdatper adapter = null;
    private PopupWindow popupWindow = null;
    static public String staticusername, savepoint, staticdeleteusername, staticpassword = "";
    private DeleteUserDialog deleteDialog;
    static public FindPassMain Viewtext;
    private static int currentpostion = 0;
    private static String temppass;
    
    public FindPassMain(Activity cActivity, IActivityManager activityMgr) {
        super(cActivity.getBaseContext(), ResUtil.getLayoutId(
            cActivity.getBaseContext(), "guild_find_password"));
        mContext = cActivity.getBaseContext();
        
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what > 0) {
                    mSendMess.setText(String.format("请%02d秒后重试", msg.what));
                } else {
                    mSendMess.setText("重新获取");
                    mSendMess.setEnabled(true);
                    timer.cancel();
                    // user_name_input.setEnabled(true);
                }
            }
        };
        
        this.activityMgr = activityMgr;
        ownerActivity = cActivity;
        inflater = LayoutInflater.from(this.getContext());
        dbHelper = DBHelper.getInstance(this.getContext());
        initView();
        
        savepoint = "0";
        Viewtext = this;
        try {
            initAccount();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private void initAccount() {
        // 先在本地sqlite 数据库中检测是否有用户名存在
        db_valid_accts = dbHelper.getAllValidAccounts();
        local_valid_accts = AccountHelper.getLocalAccountsAsArrayList(this.getContext(),true);
        AccountHelper.Local_Account account = AccountHelper
            .getLastestLoginAccountFromOldSdk(this.getContext());
        if (db_valid_accts.size() > 0) {
            DBHelper.SDK_ACCOUNT acc = db_valid_accts.get(0);
            // user_name_input.setText(acc.user_name);
            staticpassword = acc.user_password;
        } else if (local_valid_accts.size() > 0) {
            Local_Account temp = local_valid_accts
                .get(local_valid_accts.size() - 1);
            // user_name_input.setText(temp.username);
            staticpassword = temp.password;
        } else if (account.username != null && !"".equals(account.username)) {
            account.last_login_time = System.currentTimeMillis();
            account.isValid = AccountHelper.ACCOUNT_VALID;
            
            AccountHelper.updateLocalAccounts(account);
            staticpassword = account.password;
        } else {
            staticpassword = "";
        }
    }
    
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        this.postInvalidate();
        
        updateAccount();
    }
    
    private void updateAccount() {
        db_valid_accts = dbHelper.getAllValidAccounts();
        if (LoginView.chooseCurrentUser) {
            // user_name_input.setText(CommMessage.getCurrentUserName());
            staticpassword = CommMessage.currentPassword;
            temppass = CommMessage.currentPassword;
        } else if (db_valid_accts.size() > 0) {
            DBHelper.SDK_ACCOUNT acc = db_valid_accts.get(0);
            // user_name_input.setText(acc.user_name);
            staticpassword = acc.user_password;
            temppass = acc.user_password;
        } else {
            local_valid_accts = AccountHelper.getLocalAccountsAsArrayList(mContext,true);
            
            if (local_valid_accts.size() > 0) {
                Local_Account temp = local_valid_accts.get(local_valid_accts
                    .size() - 1);
                // user_name_input.setText(temp.username);
                staticpassword = temp.password;
                temppass = temp.password;
            }
        }
    }
    
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }
    
    private void initView() {
        phone_input = (EditText) this.findViewById(ResUtil.getId(mContext,
            "guild_findpass_main_phone"));
        phone_input.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        
        code_input = (EditText) this.findViewById(ResUtil.getId(mContext,
            "guild_findpass_main_mess"));
        code_input.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        
        TextView confirmBtn = (TextView) this.findViewById(ResUtil.getId(mContext,
            "guild_findpass_main_confirm"));
        confirmBtn.setOnClickListener(this);
        
        ImageView cancleBtn = (ImageView) this.findViewById(ResUtil.getId(mContext,
            "guild_findpass_main_cancle"));
        cancleBtn.setOnClickListener(this);
        
        mSendMess = (TextView) this.findViewById(ResUtil.getId(mContext,
            "guild_findpass_main_send_mess"));
        mSendMess.setOnClickListener(this);
        mSendMess.setClickable(true);
        TextView mWebus = (TextView) findViewById(ResUtil.getId(mContext,
            "guild_webus"));
        mWebus.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View v) {
        int vid = v.getId();
        
        if (vid == ResUtil.getId(mContext, "guild_webus")) {
            FancyManager.getInstance().serviceSDK.startChatPage(this
                .getContext());
        } else if (vid == ResUtil.getId(mContext,
            "guild_findpass_main_send_mess")) {
            getCodeReq();
        } else if (vid == ResUtil.getId(mContext,
            "guild_findpass_main_confirm")) {
            ucode = code_input.getText().toString().trim();
            bindReq();
        } else if (vid == ResUtil.getId(mContext,
            "guild_findpass_main_cancle")) {
            activityMgr.NewpopViewFromStack();
            activityMgr.pushViewToStack(new LoginView(ownerActivity, activityMgr));
        }
    }
    
    // 获取验证
    public void getCodeReq() {
        final String uphone = phone_input.getText().toString().trim();
        if (TextUtils.isEmpty(uphone)) {
            Toast.makeText(mContext, TipMessSingle.two_mobilenil,
                Toast.LENGTH_LONG).show();
            return;
        }
        if (!NetworkImpl.isNetworkConnected(getContext())) {
            Toast.makeText(mContext, TipMessSingle.ten_networkerr,
                Toast.LENGTH_LONG).show();
            return;
        }
        
        final Map<String, String> tempMap = GuildBaseInfo.getInstance().getRegisterSmsCodeParamsGuide(
            getContext(), uphone, "send_phone_verify");
        if (tempMap == null) {
            Toast.makeText(mContext, "传入参数有误...", Toast.LENGTH_SHORT).show();
            return;
        }
        
        bindPhoneAsyncTask = new SdkAsyncTask<String>() {
            
            @Override
            protected String doInBackground() {
                return HttpReq.doGuildRequest(tempMap);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                activityMgr.cancelWaitingDialog();
                Log.e("findpassmainret", "findpassmainret" + rst);
    
                if (rst == null) {
                    rst = "";
                }
                
                if (rst.equals("")) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr,
                        Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
                    int code = jsonState.getInt("code");
                    String msgmsg = jsonState.optString("msg");
                    if (code != 1) {
                        Toast.makeText(getContext(), msgmsg, Toast.LENGTH_LONG)
                            .show();
                        return;
                    }
                    String msg = json.getString("data");
                    JSONObject messagejson = new JSONObject(msg);
                    Log.e("findpasssfindmes", "findpasssfindmes" + messagejson);
                    
                    CommMessage.sFindCode = messagejson.getString("code");
                    Toast.makeText(mContext, "获取成功，验证码有效时间为1小时",
                        Toast.LENGTH_LONG).show();
                    
                    mSendMess.setEnabled(false);
                    timer = new Timer();
                    TimerTask timerTask = new TimerTask() {
                        int i = 55;
                        
                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.what = i--;
                            handler.sendMessage(msg);
                        }
                    };
                    timer.schedule(timerTask, 0, 1000);
                } catch (JSONException e) {
                    Log.d("BindPhone", "Server returns error msg");
                    e.printStackTrace();
                }
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() {
            }
            
        };
        bindPhoneAsyncTask.execute();
        activityMgr.showWaitingDialog();
    }
    
    // 找回密码
    public void bindReq() {
        if ((code_input.getText().toString().equals(""))) {
            Toast.makeText(mContext, TipMessSingle.two_codenil,
                Toast.LENGTH_LONG).show();
            return;
        }
        final String uphone = phone_input.getText().toString().trim();
        
        if (TextUtils.isEmpty(uphone)) {
            Toast.makeText(mContext, TipMessSingle.two_mobilenil,
                Toast.LENGTH_LONG).show();
            return;
        }
        if (!NetworkImpl.isNetworkConnected(getContext())) {
            Toast.makeText(mContext, TipMessSingle.ten_networkerr,
                Toast.LENGTH_LONG).show();
            return;
        }
        
        final Map<String, String> tempMap = GuildBaseInfo.getInstance().getFindPassUserListParams(
            getContext(), phone_input.getText().toString(), ucode, "phone_user_list");
        if (tempMap == null) {
            Toast.makeText(mContext, "传入参数有误...", Toast.LENGTH_SHORT).show();
            return;
        }
        
        bindPhoneAsyncTask = new SdkAsyncTask<String>() {
            
            @Override
            protected String doInBackground() {
                Log.e("FindPasssParam", "FindPasssParam" + tempMap.toString());
                return HttpReq.doGuildRequest(tempMap);
            }
            
            @Override
            protected void onPostExecute(String rst) {
                activityMgr.cancelWaitingDialog();
                Log.e("FindPasssrst", "FindPasssrst" + rst);
                
                if (TextUtils.isEmpty(rst)) {
                    Toast.makeText(mContext, TipMessSingle.ten_networkerr, Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    JSONObject json = new JSONObject(rst);
                    String state = json.getString("state");
                    JSONObject jsonState = new JSONObject(state);
                    String msgmsg = jsonState.optString("msg");
                    Toast.makeText(getContext(), msgmsg, Toast.LENGTH_LONG).show();
                    
                    int code = jsonState.getInt("code");
                    if (code != 1) {
                        return;
                    }
    
                    String msg = json.getString("data");
                    JSONArray array=new JSONArray(msg);
                    
                    ArrayList<String> idList=new ArrayList<>();
                    ArrayList<String> nameList=new ArrayList<>();
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject obj=new JSONObject(array.get(i).toString());
                        idList.add(obj.getString("id"));
                        nameList.add(obj.getString("name"));
                    }
                    
                    activityMgr.NewpopViewFromStack();
                    activityMgr.pushViewToStack(new AccountListViewNew(ownerActivity, activityMgr, uphone,idList,nameList));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            
            @Override
            public Activity getOwnerActivity() {
                return ownerActivity;
            }
            
            @Override
            protected void onCancelled() { }
            
        };
        bindPhoneAsyncTask.execute();
        activityMgr.showWaitingDialog();
    }
    
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
        long arg3) {
        Account account = acctArray.get(position);
        
        String username = account.user_name;
        staticpassword = account.user_password;
        // user_name_input.setText(username);
        temppass = account.user_password;
        
        LoginView.chooseCurrentUser = true;
        CommMessage.currentUserName = username;
        CommMessage.currentPassword = staticpassword;
        
        popupWindow.dismiss();
    }
    
    public class AccountShowAdatper extends BaseAdapter {
        
        ArrayList<FindPassMain.Account> array;
        
        public AccountShowAdatper(ArrayList<FindPassMain.Account> array) {
            this.array = array;
        }
    
        @Override
        public int getCount() {
            return array.size();
        }
        
        @Override
        public Object getItem(int position) {
            return array.get(position);
        }
        
        @Override
        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(final int position, View convertView,
            ViewGroup parent) {
            ViewHolder holder;
            final String curUser = array.get(position).user_name;
            
            if (convertView == null) {
                convertView = inflater.inflate(ResUtil.getLayoutId(mContext, "guild_account_list_item"), null);
                
                holder = new ViewHolder();
                holder.account = (TextView) convertView.findViewById(ResUtil
                    .getId(mContext, "guild_account_name"));
                holder.delete = (RelativeLayout) convertView
                    .findViewById(ResUtil.getId(mContext,
                        "guild_account_dele"));
                
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            
            holder.account.setText(curUser);
            
            String userandpassPP = curUser + "," + position + "";
            holder.delete.setTag(userandpassPP);
            holder.delete.setOnClickListener(new View.OnClickListener() {
                
                @Override
                public void onClick(View arg0) {
                    if (arg0 != null) {
                        String userpass = arg0.getTag().toString();
                        
                        String username = "";
                        String passowrd = "";
                        String pointsave = "0";
                        
                        String[] sourceStrArray = userpass.split(",");
                        for (int i = 0; i < sourceStrArray.length; i++) {
                            if (i == 0) {
                                username = sourceStrArray[i];
                            } else if (i == 1) {
                                passowrd = sourceStrArray[i];
                            } else if (i == 2) {
                                pointsave = sourceStrArray[i];
                            }
                            
                        }
                        staticdeleteusername = username;
                        savepoint = pointsave;
                        staticusername = username;
                        staticpassword = passowrd;
                    }
    
                    deleteDialog = new DeleteUserDialog((Activity) activityMgr, 1, new DeleteCallback() {
                        @Override
                        public void onDelete() {
                            if (acctArray != null) {
                                Local_Account accs = new Local_Account(staticusername, staticpassword, 0);
                                acctArray.remove(savepoint);
                                if (!acctArray.isEmpty()) {
                                    if (acctArray.size() == 1) {
                                        temppass = "";
                                        LoginView.editclear();
                        
                                        dbHelper.setAccountInvalid(staticusername);
                                        AccountHelper.updateLocalAccounts(accs);
                                        popupWindow.dismiss();
                                        adapter.notifyDataSetChanged();
                                        CommMessage.currentPassword = "";
                                        CommMessage.currentUserName = "";
                                        return;
                                    }
                                    FindPassMain.Account acc = acctArray.get(1);
                                    if (currentpostion == 1) {
                                        acc = acctArray.get(0);
                                    }
                                    staticpassword = acc.user_password;
                                    temppass = acc.user_password;
                                } else {
                                    staticpassword = "";
                                    temppass = "";
                                }
                                dbHelper.setAccountInvalid(staticusername);
                                AccountHelper.updateLocalAccounts(accs);
                                popupWindow.dismiss();
                                adapter.notifyDataSetChanged();
                                CommMessage.currentPassword = temppass;
                            }
                        }
                    });
                    deleteDialog.show();
    
                    if (position == 1) {
                        currentpostion = 1;
                    } else {
                        currentpostion = 0;
                    }
                }
            });
            return convertView;
        }
    }
    
    private class ViewHolder {
        
        TextView account;
        RelativeLayout delete;
    }
    
    private class Account {
        
        String user_name;
        String user_password;
        int is_valid;
        
        public Account(String user, String passwd, int isValid) {
            this.user_name = user;
            this.user_password = passwd;
            this.is_valid = isValid;
        }
    }
}
